package com.reactim.message.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.reactim.message.config.validation.ConfigurationManagementService;
import com.reactim.message.config.validation.ConfigurationHealthChecker;
import com.reactim.common.response.Result;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 配置管理控制器
 * 提供配置健康检查、监控和管理的REST API
 */
@RestController
@RequestMapping("/api/config")
@Slf4j
public class ConfigurationController {
    
    @Autowired
    private ConfigurationManagementService configManagementService;
    
    @Autowired
    private ConfigurationHealthChecker healthChecker;
    
    /**
     * 获取配置健康状态
     */
    @GetMapping("/health")
    public ResponseEntity<Result<Map<String, Object>>> getConfigurationHealth() {
        try {
            ConfigurationManagementService.ConfigurationHealthResult result = 
                configManagementService.performHealthCheck();
            
            Map<String, Object> healthData = new HashMap<>();
            healthData.put("status", configManagementService.getCurrentHealthStatus().getDescription());
            healthData.put("lastCheckTime", configManagementService.getLastHealthCheckTime());
            healthData.put("errors", result.getErrors());
            healthData.put("warnings", result.getWarnings());
            healthData.put("info", result.getInfo());
            healthData.put("hasErrors", result.hasErrors());
            healthData.put("hasWarnings", result.hasWarnings());
            
            return ResponseEntity.ok(Result.success(healthData));
            
        } catch (Exception e) {
            log.error("获取配置健康状态失败", e);
            return ResponseEntity.ok(Result.error("获取配置健康状态失败: " + e.getMessage()));
        }
    }
    
    /**
     * 执行配置健康检查
     */
    @PostMapping("/health/check")
    public ResponseEntity<Result<Map<String, Object>>> performHealthCheck() {
        try {
            ConfigurationManagementService.ConfigurationHealthResult result = 
                configManagementService.performHealthCheck();
            
            Map<String, Object> checkResult = new HashMap<>();
            checkResult.put("timestamp", LocalDateTime.now());
            checkResult.put("errors", result.getErrors());
            checkResult.put("warnings", result.getWarnings());
            checkResult.put("info", result.getInfo());
            checkResult.put("hasErrors", result.hasErrors());
            checkResult.put("hasWarnings", result.hasWarnings());
            checkResult.put("status", result.hasErrors() ? "UNHEALTHY" : 
                                   result.hasWarnings() ? "WARNING" : "HEALTHY");
            
            return ResponseEntity.ok(Result.success(checkResult));
            
        } catch (Exception e) {
            log.error("执行配置健康检查失败", e);
            return ResponseEntity.ok(Result.error("执行配置健康检查失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取配置使用统计
     */
    @GetMapping("/usage/stats")
    public ResponseEntity<Result<Map<String, Object>>> getConfigurationUsageStats() {
        try {
            Map<String, Object> stats = new HashMap<>();
            stats.put("usageStats", configManagementService.getConfigurationUsageStats());
            stats.put("lastCheckTime", configManagementService.getLastHealthCheckTime());
            stats.put("currentStatus", configManagementService.getCurrentHealthStatus().getDescription());
            
            return ResponseEntity.ok(Result.success(stats));
            
        } catch (Exception e) {
            log.error("获取配置使用统计失败", e);
            return ResponseEntity.ok(Result.error("获取配置使用统计失败: " + e.getMessage()));
        }
    }
    
    /**
     * 创建配置快照
     */
    @PostMapping("/snapshot/{name}")
    public ResponseEntity<Result<String>> createConfigurationSnapshot(@PathVariable String name) {
        try {
            configManagementService.createConfigurationSnapshot(name);
            return ResponseEntity.ok(Result.success("配置快照创建成功: " + name));
            
        } catch (Exception e) {
            log.error("创建配置快照失败", e);
            return ResponseEntity.ok(Result.error("创建配置快照失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取配置历史快照
     */
    @GetMapping("/snapshots")
    public ResponseEntity<Result<Map<String, Object>>> getConfigurationSnapshots() {
        try {
            Map<String, ConfigurationManagementService.ConfigurationSnapshot> snapshots = 
                configManagementService.getConfigurationHistory();
            
            Map<String, Object> snapshotInfo = new HashMap<>();
            snapshots.forEach((name, snapshot) -> {
                Map<String, Object> info = new HashMap<>();
                info.put("name", snapshot.getName());
                info.put("timestamp", snapshot.getTimestamp());
                snapshotInfo.put(name, info);
            });
            
            return ResponseEntity.ok(Result.success(snapshotInfo));
            
        } catch (Exception e) {
            log.error("获取配置历史快照失败", e);
            return ResponseEntity.ok(Result.error("获取配置历史快照失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取配置健康摘要（用于监控仪表板）
     */
    @GetMapping("/health/summary")
    public ResponseEntity<Result<Map<String, Object>>> getHealthSummary() {
        try {
            ConfigurationHealthChecker.ConfigurationHealthSummary summary = 
                healthChecker.getHealthSummary();
            
            Map<String, Object> summaryData = new HashMap<>();
            summaryData.put("status", summary.getStatus());
            summaryData.put("details", summary.getDetails());
            summaryData.put("timestamp", LocalDateTime.now());
            
            return ResponseEntity.ok(Result.success(summaryData));
            
        } catch (Exception e) {
            log.error("获取配置健康摘要失败", e);
            return ResponseEntity.ok(Result.error("获取配置健康摘要失败: " + e.getMessage()));
        }
    }
    
    /**
     * 记录配置使用情况
     */
    @PostMapping("/usage/record")
    public ResponseEntity<Result<String>> recordConfigurationUsage(@RequestParam String configPath) {
        try {
            configManagementService.recordConfigurationUsage(configPath);
            return ResponseEntity.ok(Result.success("配置使用记录成功"));
            
        } catch (Exception e) {
            log.error("记录配置使用情况失败", e);
            return ResponseEntity.ok(Result.error("记录配置使用情况失败: " + e.getMessage()));
        }
    }
}